# -*- coding: utf-8 -*-
# @Time    : 2018-05-29 15:07
# @Author  : Yang Feng
# @Email   : yangfeng@bbdservice.com
# @File    : Rule19_CreditAccountStatus_Check.py
# @Software: PyCharm


'''eof
name:征信账户状态校验
code:CreditAccountStatus_Check
tableName:
columnName:
groups:准入>个人征信
dependencies:IC
type:常用指标
datasourceType:在线指标
description:
eof'''


import sys
import json
import datetime
import traceback
import re
reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', None, 'null', '/', 'Null']

def FormatData(tableName):
    try:
        icr = json.loads(IC[0]["icr"])[tableName]
        return icr if isinstance(icr, list) and len(icr) > 0 else [{}]
    except:
        return [{}]


def ConvertDataType(dataValue, dataType):
    returnData = None
    if dataType == 'float':
        try:
            returnData = float(dataValue) if float(dataValue) >= 0 else None
        except:
            returnData = None
    elif dataType == 'None':
        returnData = 0 if dataValue is None else dataValue
    return returnData


def CreditAccountStatusCheckPre(*arg):
    try:
        returnList = []
        # 特殊交易
        icrSpecialTradeLoanList = FormatData(arg[0])
        # 贷款
        icrLoancardInfo002CardList = FormatData(arg[1])
        if icrSpecialTradeLoanList == [{}] and icrLoancardInfo002CardList == [{}]:
            return None
        icrSpecialTradeDict = {}
        for icrSpecialTradeLoan in icrSpecialTradeLoanList:
            try:
                tradeType = icrSpecialTradeLoan.get("TradeType")
                account = icrSpecialTradeLoan.get("Account")
                if account not in null_type_list and tradeType not in null_type_list:
                    if icrSpecialTradeDict.has_key(account):
                        tradeTypeAdd = icrSpecialTradeDict[account]
                        tradeTypeAdd.append(tradeType)
                        icrSpecialTradeDict.update({account: tradeTypeAdd})
                    else:
                        icrSpecialTradeDict.setdefault(account, [tradeType])
            except:
                continue
        for icrLoancardInfo002Card in icrLoancardInfo002CardList:
            try:
                account = icrLoancardInfo002Card.get("Account")
                state = icrLoancardInfo002Card.get("State")
                latest24State = icrLoancardInfo002Card.get("Latest24State")
                accountPre = icrSpecialTradeDict.get(account) if icrSpecialTradeDict.get(account) is not None else ''
                if account in null_type_list and state in null_type_list and latest24State in null_type_list:
                    returnList.append(None)
                elif state == u"呆账" or "Z" in latest24State.upper() or "D" in latest24State.upper() \
                        or u"担保人代还" in accountPre or u"以资抵债" in accountPre \
                        or (state == u"冻结" and arg[1] != "ICRLoanInfo002*Loan"):
                    returnList.append(1)
                else:
                    returnList.append(0)
            except:
                returnList.append(None)
                continue
        returnListNotNone = filter(lambda x:x is not None, returnList)
        if len(returnListNotNone) == 0:
            return None
        else:
            return sum(returnListNotNone)
    except:
        return None


def CreditAccountStatusCheck():
    try:
        returnList = []
        # 逾期及违约信息概要
        icrFellbackSummary = FormatData("ICRFellbackSummary")
        # Factor1
        # 呆账笔数
        count = ConvertDataType(icrFellbackSummary[0].get("Count"), 'float')
        # 资产处置信息汇总笔数
        count2 = ConvertDataType(icrFellbackSummary[0].get("Count2"), 'float')
        # 保证人代偿信息汇总笔数
        count3 = ConvertDataType(icrFellbackSummary[0].get("Count3"), 'float')
        if count is None and count2 is None and count3 is None:
            returnList.append(None)
        else:
            returnList.append(ConvertDataType(count, 'None')+ConvertDataType(count2, 'None')+ConvertDataType(count3, 'None') )

        # Factor2（贷款信息）
        factor2 = CreditAccountStatusCheckPre(*("ICRSpecialTrade*Loan", "ICRLoanInfo002*Loan"))
        returnList.append(factor2)
        # Factor3（贷记卡）
        factor3 = CreditAccountStatusCheckPre(*("ICRSpecialTrade*Card", "ICRLoancardInfo002*Card"))
        returnList.append(factor3)
        # Factor4（准贷记卡）
        factor4 = CreditAccountStatusCheckPre(*("ICRSpecialTrade*Std", "ICRStdLoancardInfo002*Std"))
        returnList.append(factor4)
        returnListNotNone = filter(lambda x: x is not None, returnList)
        if len(returnListNotNone) == 0:
            return u"缺失值"
        else:
            return sum(returnListNotNone)
    except:
        return u"缺失值"


result = CreditAccountStatusCheck()